package com.NetSunWeiQin.chapter03.multithread2;

import java.io.*;
import java.net.*;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class ThreadGroupEchoServer {
    private int port = 8000;
    private ServerSocket serverSocket;
    private ThreadPool threadPool;
    private final int POOL_SIZE = 2;

    public ThreadGroupEchoServer() throws IOException {
        serverSocket = new ServerSocket(port);

        //  threadPool = new ThreadPool(Runtime.getRuntime().availableProcessors() * POOL_SIZE);
        threadPool = new ThreadPool(2);

        System.out.println("server started............");
    }

    public void service() {

        Callable<String> call = () -> {
            while (true) {
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                String s = br.readLine();
                if ("exit".equals(s)) {
                    return "exit";
                }
            }
        };

        FutureTask<String> task = new FutureTask<>(call);
        Thread t = new Thread(task);
        t.start();
        while (true) {

            try {
                String s = task.get();
                Socket socket = null;
                if ("exit".equals(s)) {
                    threadPool.join();
                    break;
                }
                socket = serverSocket.accept();
                threadPool.execute(new Handler(socket));

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String args[]) throws IOException {
        new ThreadGroupEchoServer().service();
    }
}

class Handler implements Runnable {
    private Socket socket;

    public Handler(Socket socket) {
        this.socket = socket;
    }

    private PrintWriter getWriter(Socket socket) throws IOException {
        OutputStream socketOut = socket.getOutputStream();
        return new PrintWriter(socketOut, true);
    }

    private BufferedReader getReader(Socket socket) throws IOException {
        InputStream socketIn = socket.getInputStream();
        return new BufferedReader(new InputStreamReader(socketIn));
    }

    public String echo(String msg) {
        return "echo:" + msg;
    }

    public void run() {
        try {
            System.out.println("New connection accepted " + socket.getInetAddress() + ":" + socket.getPort());
            BufferedReader br = getReader(socket);
            PrintWriter pw = getWriter(socket);

            String msg = null;
            while ((msg = br.readLine()) != null) {
                System.out.println(" INFO " + Thread.currentThread().getName() + " handle request which  from " + socket.getInetAddress()+ ":" + socket.getPort() + ">" + msg);

                pw.println(echo(msg));
                if (msg.equals("bye"))
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (socket != null) socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


